package api

import (
	"GopherFocus/app/model"
	"GopherFocus/app/system/index/internal/define"
	"GopherFocus/app/system/index/internal/service"
	"GopherFocus/library/response"
	"github.com/gogf/gf/net/ghttp"
)

var Login = loginApi{}

type loginApi struct{}

// 首页
func (a *loginApi) Index(r *ghttp.Request) {
	service.View.Render(r, model.View{})
}

// 提交登录
func (a *loginApi) Do(r *ghttp.Request) {
	var (
		req *define.UserLoginReq
	)
	if err := r.Parse(&req); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	if !service.Captcha.VerifyAndClear(r, model.CaptchaStoreKey, req.Captcha) {
		response.JsonExit(r, 1, "请输入正确的验证码")
	}
	if err := service.User.Login(r.Context(), req.UserLoginInput); err != nil {
		response.JsonExit(r, 1, err.Error())
	} else {
		// 识别并跳转到登录前页面
		// referrer表示发起当前请求的url页面地址
		loginReferer := service.Session.GetLoginReferer(r.Context())
		if loginReferer != "" {
			_ = service.Session.RemoveLoginReferer(r.Context())
		}
		response.JsonExit(r, 0, "", loginReferer)
	}
}
